# @author Paul Stein apexrubydev@gmail.com
#
# The method called by the user. Routes the args and array to one of the other functions.
# @param [Array] The array to be checked for the terms.
# @param [Object] There can be a single term, or an array of terms.
def two_d(array_2d, term)
  if term.is_a?(Array)
    two_dm(array_2d, term)
  else
    two_ds(array_2d, term)
  end
end

# The method called by 'two_d' if there was a SINGLE term.
# @param [Array] The 2D array to be checked for the term.
# @param [Object] A single term.
# @return [Hash] A hash with the term as key and an array of indices.
def two_ds(array_2d, term)
  # Find the sub arrays which include the term.
  f_index_array = []
  array_2d.each do |line| 
    result = line.include?(term)
    if result == true
      f_index_array << array_2d.index(line)  
    end
  end

  # Create an array of arrays with the indices in [row, col] order.
  combined_index_array = []
  f_index_array.each do |first|
    counter = 0
    array_2d[first].each do |item|
      result = item == term
      if result == true
        combined_index_array << [first,counter]
      end
    counter += 1
    end
  end
  # Make a hash from the term and the array of indices for that term in the origional 2D array.
  return {term => combined_index_array}
end

# The method called by 'two_d' if there was an ARRAY of terms.
# @param [Array] The 2D array to be checked for the term.
# @param [Array] The array of terms.
# @return [Hash] A hash of all terms and their indices in {term => [[index],[index]...]} format.
# Simply passes each term in the term array to two_ds and merges the returned hash into the combined hash.
def two_dm(array_2d, terms)
  results = Hash.new {}
  terms.each do |term|
    results = results.merge(two_d(array_2d,term))
  end
  return results
end
